package com.lihao.wanandroid.ui.home.recommend

import android.os.Bundle
import android.view.LayoutInflater
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.kingja.loadsir.core.LoadService
import com.lihao.jetpackcore.ext.getViewModel
import com.lihao.jetpackcore.ext.nav
import com.lihao.jetpackcore.ext.parseState
import com.lihao.jetpackcore.ext.util.dp2px
import com.lihao.jetpackcore.util.ToastUtil
import com.lihao.wanandroid.R
import com.lihao.wanandroid.app.base.BaseFragment
import com.lihao.wanandroid.app.ext.LoadServiceInit
import com.lihao.wanandroid.app.ext.setAdapterAnimation
import com.lihao.wanandroid.app.ext.setErrorText
import com.lihao.wanandroid.app.util.VibrateUtils
import com.lihao.wanandroid.app.weight.banner.HomeBannerViewHolder
import com.lihao.wanandroid.app.weight.recyclerview.SpaceItemDecoration
import com.lihao.wanandroid.data.model.BannerResponse
import com.lihao.wanandroid.data.model.CollectEvent
import com.lihao.wanandroid.ui.collect.CollectViewModel
import com.lihao.wanandroid.ui.web.WebFragment
import com.zhpan.bannerview.BannerViewPager
import kotlinx.android.synthetic.main.fragment_recommend.*
import me.hgj.jetpackmvvm.demo.app.weight.loadCallBack.EmptyCallback
import me.hgj.jetpackmvvm.demo.app.weight.loadCallBack.ErrorCallback
import me.hgj.jetpackmvvm.demo.app.weight.loadCallBack.LoadingCallback

/**
 * Created by lihao on 2020/5/20.
 * Describe: 首页文章列表Fragment
 */
class RecommendFragment : BaseFragment<RecommendViewModel>() {

    //界面状态管理者
    private lateinit var loadsir: LoadService<Any>

    private val collectViewModel: CollectViewModel by lazy {
        getViewModel<CollectViewModel>()
    }

    private val mAdapter: ArticleAdapter by lazy {
        ArticleAdapter().apply {
            setAdapterAnimation(2)
            loadMoreModule.setOnLoadMoreListener {
                mViewModel.getHomeData(false)
            }
            setOnItemClickListener { adapter, view, position ->
                val bundle = Bundle()
                bundle.putParcelable("articleData", data[position])
                nav().navigate(R.id.action_to_webFragment, bundle)
            }
            setOnItemChildClickListener { adapter, view, position ->
                when (view.id) {
                    R.id.tvCollect -> {
                        VibrateUtils.vibrate(40)
                        if (shareViewModel.isLogin.value) {
                            if (mAdapter.data[position].collect) {
                                collectViewModel.uncollectArticle(mAdapter.data[position].id)
                            } else {
                                collectViewModel.collectArticleIn(mAdapter.data[position].id)
                            }
                        } else {
                            nav().navigate(R.id.action_to_loginFragment)
                        }
                    }
                }
            }
        }
    }

    override fun layoutId() = R.layout.fragment_recommend

    override fun initView(savedInstanceState: Bundle?) {
        loadsir = LoadServiceInit(recyclerView) {
            loadsir.showCallback(LoadingCallback::class.java)
            mViewModel.getBannerData()
            mViewModel.getHomeData(true)
        }
        recyclerView.run {
            layoutManager = LinearLayoutManager(context)
            addItemDecoration(SpaceItemDecoration(0, dp2px(8), false))
            adapter = mAdapter
        }
        swipeRefresh.setOnRefreshListener {
            mViewModel.getBannerData()
            mViewModel.getHomeData(true)
        }
    }

    override fun lazyLoadData() {
        loadsir.showCallback(LoadingCallback::class.java)
        mViewModel.getBannerData()
        mViewModel.getHomeData(true)
    }

    override fun createObserver() {
        //首页文章列表数据
        mViewModel.homeDataState.observe(viewLifecycleOwner, Observer {
            swipeRefresh.isRefreshing = false
            if (it.isSuccess) {
                when {
                    it.isFirstEmpty -> {
                        // 显示空布局
                        loadsir.showCallback(EmptyCallback::class.java)
                    }
                    it.isRefresh -> {
                        loadsir.showSuccess()
                        mAdapter.setList(it.listData)
                    }
                    else -> {
                        loadsir.showSuccess()
                        mAdapter.addData(it.listData)
                    }
                }
                if (it.hasMore) {
                    mAdapter.loadMoreModule.loadMoreComplete()
                } else {
                    mAdapter.loadMoreModule.loadMoreEnd()
                }
            } else {
                // 失败
                if (it.isRefresh) {
                    //如果是第一页，则显示错误界面，并提示错误信息
                    loadsir.setErrorText(it.errorMsg)
                    loadsir.showCallback(ErrorCallback::class.java)
                } else {
                    mAdapter.loadMoreModule.loadMoreFail()
                }
            }
        })
        // 首页轮播图
        mViewModel.bannerData.observe(this, Observer { resultState ->
            parseState(resultState, { data ->
                if (!mAdapter.hasHeaderLayout()) {
                    val headerView =
                        LayoutInflater.from(context).inflate(R.layout.item_home_banner, null)
                            .apply {
                                val banner =
                                    findViewById<BannerViewPager<BannerResponse, HomeBannerViewHolder>>(
                                        R.id.banner
                                    )
                                banner.setHolderCreator { HomeBannerViewHolder() }
                                    .setOnPageClickListener {
                                        val bundle = Bundle()
                                        bundle.putParcelable(
                                            WebFragment.KEY_BANNER,
                                            data[it]
                                        )
                                        nav().navigate(R.id.action_to_webFragment, bundle)
                                    }.create(data.toList())
                            }
                    mAdapter.addHeaderView(headerView)
                }
            }, {
                ToastUtil.showShort(context, it.errorMsg)
            })
        })
        collectViewModel.collectState.observe(this, Observer {
            if (it.isSuccess) {
                ToastUtil.showShort(context, if (it.collect) "收藏成功！" else "取消收藏！")
                eventViewModel.collect.value = CollectEvent(it.id, it.collect)
            } else {
                ToastUtil.showShort(context, it.errorMsg)
            }
        })
        shareViewModel.run {
            userInfo.observe(viewLifecycleOwner, Observer {
                if (it != null) {
                    it.collectIds.forEach { id ->
                        for (item in mAdapter.data) {
                            if (id.toInt() == item.id) {
                                item.collect = true
                                break
                            }
                        }
                    }
                } else {
                    for (item in mAdapter.data) {
                        item.collect = false
                    }
                    mAdapter.notifyDataSetChanged()
                }
            })
        }
        eventViewModel.collect.observe(this, Observer {
            for (index in mAdapter.data.indices) {
                if (mAdapter.data[index].id == it.id) {
                    mAdapter.data[index].collect = it.collect
                    mAdapter.notifyDataSetChanged()
                    break
                }
            }
        })
    }
}